<template>
    <a-form ref='formRef' :label-col='{span : 5}' :model='formData'>
        <a-form-item style='display:none' name='id'>
            <a-input type='hidden' v-model:value='formData.id' />
        </a-form-item>
        <a-form-item label='名称' name='name' :rules="[{required : true, message : '请填写名称'}]">
            <a-input type='text' v-model:value='formData.name' />
        </a-form-item>
        <a-form-item label='消息模板' name='file' :rules="[{required : true, message : '请上传模板'}]">
            <a-upload :max-count="1" v-model:file-list='fileList' :beforeUpload='beforeUpload' :customRequest='uploadCover'>
                <template v-if='fileList.length == 0'>
                    <a-button><UploadOutlined /></a-button>
                </template>
            </a-upload>
        </a-form-item>
    </a-form>
</template>

<script lang="ts" setup>
    import { saveApi, uploadApi } from '@/api/MessageTemplate';
        import { UploadOutlined } from '@ant-design/icons-vue';
        import { ref } from 'vue';


    const props = defineProps<{
        row? : any;
        category? : number
    }>()

    const fileList = ref<any[]>([])

    const formRef = ref()

    
    const formData = ref({
        id : 0,
        name : '',
        file : '',
    })

    if(props.row) {
        for(let k in props.row) {
            if(k in formData.value) {
                formData.value[k] = props.row[k]
            }
        }

        if(props.row.file) {
            fileList.value[0] = {
                status : 'done',
                url : import.meta.env.B_NET_STATIC_URL + props.row.file
            }
        }

    }

    async function submit() {
        let params  = await formRef.value.validate()
        console.log(params)
        if('sort' in params && params.sort === '') {
            params.sort = 0
        }


        return saveApi(params)
    }


    function uploadCover(e) {
        uploadApi(e.file).then(res => {
            fileList.value[0].status = 'done'
            fileList.value[0].url = import.meta.env.B_NET_STATIC_URL + res.data
            formData.value.file = res.data
        })
    }

    function beforeUpload(file:File, field:FormField) {
        return true
    }


    defineExpose({
        submit
    })
</script>